package uk.ac.cam.bt288.DesktopApp;

import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
import javax.swing.JLabel;

public class BluetoothThread implements Runnable{
	private static JLabel status = null;
	/** Constructor */
	public BluetoothThread(JLabel s) {
		status = s;
	}

	@Override
	public void run() {
		waitForConnection();		
	}

	/** Waiting for connection from devices */
	private void waitForConnection() {
		// retrieve the local Bluetooth device object
		LocalDevice local = null;

		StreamConnectionNotifier notifier;
		StreamConnection connection = null;

		// setup the server to listen for connection
		try {
			local = LocalDevice.getLocalDevice();
			local.setDiscoverable(DiscoveryAgent.GIAC);

			UUID uuid = new UUID("0000110100001000800000805F9B34FA", false);

            String url = "btspp://localhost:" + uuid.toString() + ";name=DemoApplication";
            notifier = (StreamConnectionNotifier)Connector.open(url);
		} catch (Exception e) {
            e.printStackTrace();
            return;
        }

		// waiting for connection
		while(true) {
			try {
				System.out.println("waiting for connection...");
				status.setText("Waiting for connection");
	            connection = notifier.acceptAndOpen();
	            System.out.println("Connecting");
	            Thread processThread = new Thread(new BluetoothProcessConnection(connection, status));
	            processThread.start();

			} catch (Exception e) {
				e.printStackTrace();
				return;
			}
		}
	}
}

